package main

import (
	"fmt"
	"sort"
)

func main() {
	var cmap map[string] string

	if cmap == nil {
		fmt.Println("cmap is nil, so make to cmap!")
		cmap = make(map[string]string)
	}

	cmap ["a"] = "a"
	cmap ["b"] = "b"
	
	fmt.Println(cmap)

	for c := range cmap {
		fmt.Println(cmap[c])
	}

	t ,ok := cmap ["n"]

	if ok {
		fmt.Println("key=n,value=", t)
	} else {
		fmt.Println("key=n不存在")
	}
	//删除元素 a
	delete(cmap,"a")



	//mapReverse()

	//sortMap()

	//sliceMap()

	complexMap()
}
/*
 倒置
 */
func mapReverse()  {
	m := map[int]string{1:"a",2:"b"}
	fmt.Println(m)

	m2 := make(map[string]int)

	for k,v := range m {
		m2 [v] = k
	}

	fmt.Println(m2)

}

func sortMap()  {
	var a map[string]int = make(map[string]int, 10)
	for i := 0; i < 10; i++ {
		key := fmt.Sprintf("key%d", i)
		a[key] = i
	}
	var keys []string
	for key, _ := range a {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	for _, key := range keys {
		fmt.Printf("key:%s=%d\n", key, a[key])
	}
}

/**
  map类型的切片
 */
func sliceMap(){
	var mapSlice []map[string]int
	mapSlice = make([]map[string]int, 5)
	fmt.Println("before map init")
	for index, value := range mapSlice {
		fmt.Printf("index:%d value:%v\n", index, value)
	}
	fmt.Println()
	mapSlice[0] = make(map[string]int, 10)
	mapSlice[0]["a"] = 1000
	mapSlice[0]["b"] = 2000
	mapSlice[0]["c"] = 3000
	mapSlice[0]["d"] = 4000
	mapSlice[0]["e"] = 5000
	fmt.Println("after map init")
	for index, value := range mapSlice {
		fmt.Printf("index:%d value:%v\n", index, value)
	}
}

/**
  复杂map
 */
func complexMap()  {
	var m map[int]map[int]string
	m = make(map[int]map[int]string)
	val,ok := m[2][1]
	if !ok {
		m[2] = make(map[int]string)
	}

	m[2][1] = "set val"
	val = m[2][1]
	fmt.Println("复杂map->",val)
}